﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace SimpleWpfTemplate
{
    #region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 版权所有 (c) 2025   保留所有权利。
 * CLR版本：4.0.30319.42000
 * 公司名称：
 * 命名空间：SimpleWpfTemplate
 * 唯一标识：646a668a-fae5-4379-a00e-8b927ecc9127
 * 文件名：RichTextBoxHelper
 * 
 * 创建者：dongming
 * 电子邮箱：15688277399@163.com
 * 创建时间：2025/6/13 13:54:31
 * 版本：V1.0.0
 * 描述：
 *----------------------------------------------------------------*/
 #endregion << 版 本 注 释 >>
    class RichTextBoxHelper
    {
		public static readonly DependencyProperty DocumentXamlProperty =
	   DependencyProperty.RegisterAttached(
		   "DocumentXaml",
		   typeof(string),
		   typeof(RichTextBoxHelper),
		   new FrameworkPropertyMetadata(
			   string.Empty,
			   FrameworkPropertyMetadataOptions.AffectsRender,
			   OnDocumentXamlChanged));

		public static string GetDocumentXaml(DependencyObject obj)
		{
			return (string)obj.GetValue(DocumentXamlProperty);
		}

		public static void SetDocumentXaml(DependencyObject obj, string value)
		{
			obj.SetValue(DocumentXamlProperty, value);
		}

		private static void OnDocumentXamlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			if (d is RichTextBox rtb && e.NewValue is string xaml)
			{
				try
				{
					// 转换XAML字符串为FlowDocument
					var flowDoc = new FlowDocument();
					var range = new TextRange(flowDoc.ContentStart, flowDoc.ContentEnd);
					using (var stream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(xaml)))
					{
						range.Load(stream, DataFormats.Text);
					}
					rtb.Document = flowDoc;
				}
				catch
				{
					rtb.Document = new FlowDocument();
				}
			}
		}
	}
}
